package cn.thornbird.orgsync.model;

import lombok.Data;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.List;

@Data
public class PageList<T> {

    public static final int DEFAULT_PAGE_SIZE = 10;

    public static final int MAX_PAGE_SIZE = 0x7fff;

    private int current;

    private int pageSize;

    private int pageCount;

    private long total;

    private List<T> list = new ArrayList<>();

    public static <T> PageList<T> convertPage(Page<T> page) {
        PageList<T> pageList = new PageList<>();
        pageList.setCurrent(page.getNumber());
        pageList.setPageSize(page.getSize());
        pageList.setPageCount(page.getTotalPages());
        pageList.setTotal(page.getTotalElements());
        pageList.setList(page.getContent());
        return pageList;
    }

    public static <T> PageList<T> createEmptyPageList() {
        PageList<T> pageList = new PageList<>();
        pageList.setCurrent(0);
        pageList.setPageSize(DEFAULT_PAGE_SIZE);
        pageList.setPageCount(0);
        pageList.setTotal(0);
        pageList.setList(new ArrayList<>());
        return pageList;
    }

    public static <T, O> PageList<T> createEmptyPageList(Page<O> page) {
        PageList<T> pageList = new PageList<>();
        pageList.setCurrent(page.getNumber());
        pageList.setPageSize(page.getSize());
        pageList.setPageCount(page.getTotalPages());
        pageList.setTotal(page.getTotalElements());
        pageList.setList(new ArrayList<>());
        return pageList;
    }

    public static Pageable generatePageable(Integer pageNumber, Integer pageSize) {
        return PageRequest.of(pageNumber == null ? 0 : pageNumber,
                pageSize == null ? DEFAULT_PAGE_SIZE : Math.max(pageSize, 1));
    }

    public static Pageable generatePageable(Integer pageNumber, Integer pageSize, Sort sort) {
        return PageRequest.of(pageNumber == null ? 0 : pageNumber,
                pageSize == null ? DEFAULT_PAGE_SIZE : Math.max(pageSize, 1), sort);
    }

}
